package com.zcbl.toolkit.http.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;

/**
 * @author he peng
 * @create 2018/4/4 9:36
 * @see
 */
public class IPAddressUtils {

    private static final String UNKNOWN_IP = "unknown";

    private IPAddressUtils() {}


    public static String getRequestIP(HttpServletRequest request) {
        Assert.notNull(request , "request == null");
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isBlank(ip) || StringUtils.equalsIgnoreCase(UNKNOWN_IP , ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || StringUtils.equalsIgnoreCase(UNKNOWN_IP , ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || StringUtils.equalsIgnoreCase(UNKNOWN_IP , ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(ip) || StringUtils.equalsIgnoreCase(UNKNOWN_IP , ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(ip) || StringUtils.equalsIgnoreCase(UNKNOWN_IP , ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
